/* 10. 查询读者 */

const CHECK = require("../myUtil/formatCheck");
const db = require("../../coSqlite3");
const HTM = require("../myUtil/lib").html;

exports.queryUser = function* (req, res) {
    console.log("----------------------10. 查询读者\n");
    let rID = req.body.rID;
    let rName = req.body.rName;
    let rSex = req.body.rSex;
    let rDept = req.body.rDept;
    let rGrade0 = req.body.rGrade0;
    let rGrade1 = req.body.rGrade1;

    let htm = HTM.tableBegin + HTM.tableEnd + '提交的参数有误：';

    if (rID.length > 8) {
        return HTM.head + htm + '证号长度不能超过8个字符' + HTM.end;
    }

    if (rName.length > 10) {
        return HTM.head + htm + "姓名长度不能超过10个字符" + HTM.end;
    }

    if ('' != rSex && '女' != rSex && '男' != rSex) {
        return HTM.head + htm + '性别必须是男或女' + HTM.end;
    }

    if (rDept.length > 10) {
        return HTM.head + htm + "院系长度不能超过10个字符" + HTM.end;
    }

    if ('' != rGrade0 && CHECK.isNotPositiveInt(rGrade0)) {
        return HTM.head + htm + '年级必须是正整数' + HTM.end;
    }

    if ("" != rGrade1 && CHECK.isNotPositiveInt(rGrade1)) {
      return HTM.head + htm + "年级必须是正整数" + HTM.end;
    }


    let array = [rID, rName, rSex, rDept, rGrade0, rGrade1];
    let args = [];
    let trueORFalse = [];
    for (let item of array) {
        if (item != '') {
            trueORFalse.push(true);
            args.push(item);
            continue;
        }
        trueORFalse.push(false);
    }
    // console.log(args);
    /* if (0 == args.length) {
        console.log('');
        htm = HTM.tableBegin + HTM.tableEnd;
        return HTM.head + htm + HTM.end;
    } */
    
    let rows;
    htm = HTM.tableBegin + HTM.tableEnd + '数据库执行失败：';
    try {
        rows = yield db.execSQL(
            "SELECT * FROM reader WHERE 1 == 1 " +  
            (trueORFalse[0] ? "AND rID LIKE '%'||?||'%' " : "") +
            (trueORFalse[1] ? "AND rName LIKE '%'||?||'%' " : "") +
            (trueORFalse[2] ? "AND rSex LIKE '%'||?||'%' " : "") +
            (trueORFalse[3] ? "AND rDept LIKE '%'||?||'%' " : "") +
            (trueORFalse[4] ? "AND rGrade>=? " : "") +
            (trueORFalse[5] ? "AND rGrade<=? " : ""),
            args);
    } catch (error) {
        return HTM.head + htm + error + HTM.end;
    }

    if (0 == rows.length) {
        htm = HTM.tableBegin + HTM.tableEnd;
        return HTM.head + htm + HTM.end;
    }

    htm = '';
    for (let row of rows) {
        htm +=
          "<tr><td>" +
          row.rid +
          "</td><td>" +
          row.rname +
          "</td><td>" +
          row.rsex +
          "</td><td>" +
          row.rdept +
          "</td><td>" +
          row.rgrade
          "</td></tr>\n";
    }
    // console.log(HTM.head + htm + HTM.tableEnd + HTM.end);
    return HTM.head + HTM.tableBegin + htm + HTM.tableEnd + HTM.end;
}
